package com.stone.framework.gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.stone.framework.core.context.UserContext;

import brave.Span;
import brave.Tracer;
import reactor.core.publisher.Mono;

@Component
public class ZipkinTracingGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private Tracer tracer;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Span currentSpan = this.tracer.currentSpan();
        if (currentSpan != null) {
            String username = UserContext.getUsername().orElse("anonymous");
            currentSpan.tag("custom.user", username);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -10;
    }

}
